package com.baidu.config;

import com.alibaba.fastjson.JSON;
import com.baidu.pojo.ResultVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;


/**
 * gateway拦截器
 *
 */
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered{

	@Autowired
	private StringRedisTemplate stringRedisTemplate;
	@Override
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
		ServerHttpResponse response = exchange.getResponse();
		ServerHttpRequest request = exchange.getRequest();
		String path = request.getURI().getPath();
		//如果是登陆接口 就直接放过校验
		if(path.indexOf("/api/user")>=0){
			return chain.filter(exchange);
		}
		String token = stringRedisTemplate.opsForValue().get("token");
		if (!StringUtils.isEmpty(token)) {
			// 如果token不为空，则直接放行
			return chain.filter(exchange);
		} else {
			// token为空，则返回json到前台，请求结果返回401（权限不足）
			ResultVo resultVo = new ResultVo();
			resultVo.setCode(300);
			resultVo.setMsg("token过期");
			resultVo.setData(null);
			byte[] bits = JSON.toJSONString(resultVo).getBytes(StandardCharsets.UTF_8);
			DataBuffer buffer = response.bufferFactory().wrap(bits);
			response.setStatusCode(HttpStatus.UNAUTHORIZED);
			//指定编码，否则在浏览器中会中文乱码
			response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
			return response.writeWith(Mono.just(buffer));
		}
	}

	@Override
	public int getOrder() {
		return -100;
	}
}
